// 2.2
/**
 *
 树的扁平化, 可参考下⾯的输⼊样例和输出样例
 */

function traverseTree(root) {
    const queue = [root]; // 将根节点加入队列
    while (queue.length > 0) {
        const node = queue.shift(); // 从队列中取出第一个节点
        console.log(node.val); // 访问当前节点的值
        node.children.forEach(child => {
            queue.push(child); // 将子节点加入队列
        });
    }
}

traverseTree(getData())

function getData() {
    let inner = {
        val: "A",
        id: 1,
        children: [
            {
                val: "B",
                id: 2,
                children: [
                    {
                        val: "D",
                        id: 4,
                        children: [],
                    },
                    {
                        val: "E",
                        id: 5,
                        children: [],
                    },
                ],
            },
            {
                val: "C",
                id: 3,
                children: [
                    {
                        val: "F",
                        id: 6,
                        children: [],
                    },
                ],
            },
        ],
    };

    return inner
}


// [
// { val: 'A', id: 1, parentId: null },
//     { val: 'B', id: 2, parentId: 1 },
//     { val: 'D', id: 4, parentId: 2 },
//     { val: 'E', id: 5, parentId: 2 },
//     { val: 'C', id: 3, parentId: 1 },
//     { val: 'F', id: 6, parentId: 3 }
// ]

let resArr = []

function flattenTree(tree, parentId, val) {
    // 你的实现...
    console.log('flattenTree1==', tree, tree.length)
    let arr = Object.entries(tree)
    console.log('flattenTree2==', arr)
    // 0:(2) ['val', 'A']
    // 1:(2) ['id', 1]
    // 2:(2) ['children', Array(2)]
    let len = arr.length

    for (let keys in tree) {
        if (keys === 'children') {
            console.log('tree[i].children===', tree[keys])
            // parentId = tree[item]
            flattenTree(tree[keys], tree.id)
        }
        let treeItem = {
            val: val, id: tree.id, parentId: parentId
        }
        resArr.push(treeItem)
    }
    // for (let i = 0; i < tree.length; i++) {
    //     console.log('flattenTree2==', tree[i])

    // }
}


flattenTree(getData(), null, getData().id)

console.log('resArr=', resArr)


